package com.tool.lock.reen;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 酒徒
 * @Version 1.0
 * @data 2025/7/1 18:34
 */

public class ReentrantTest {
    private ReentrantLock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();
    private static boolean isPrintA = true;
    public static void main(String[] args) {
        ReentrantTest reentrantLock = new ReentrantTest();
        reentrantLock.printA();
        reentrantLock.printB();
    }

    public void printA() {
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                lock.lock();
                try {
                    while (!isPrintA) {
                        condition.await();
                    }
                    System.out.println("A");
                    isPrintA = false;
                    condition.signal();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    lock.unlock();
                }
            }
        }).start();
    }

    public void printB() {
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                lock.lock();
                try {
                    while (isPrintA) {
                        condition.await();
                    }
                    System.out.println("B");
                    isPrintA = true;
                    condition.signal();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    lock.unlock();
                }
            }
        }).start();
    }


}



